﻿using HLStock.MyExcep;
using HLStock.MyType;
using System.Data;
using System.Reflection;

namespace HLStock.DBAccess
{
    internal class PropValueSetter
    {
        public PropValueSetter(PropertyInfo property)
        {
            PropName = property.Name;
            Property = property;
            if (Property.PropertyType.IsAssignableTo(typeof(IDynamicSet)))
            {
                dynamicSet = (IDynamicSet)Property.PropertyType.Assembly.CreateInstance(Property.PropertyType.FullName!)!;
            }
        }
        internal string PropName { get; private set; }
        PropertyInfo Property;
        IDynamicSet? dynamicSet;
        internal void Set(IDataReader dataReader, object record)
        {
            try
            {
                object o = dataReader[PropName.ToUpper()];
                if (o.GetType() == typeof(DBNull))
                {
                    Property.SetValue(record, null);
                }
                else if (dynamicSet != null)
                {
                    Property.SetValue(record, dynamicSet.CreateWithVal(o));
                }
                else
                {
                    Property.SetValue(record, o);
                }
            }
            catch (Exception ex)
            {
                throw new MyDataOptException(ex.Message);
            }
        }
    }
}
